package com.jung.news.action;


import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jung.common.Constants;
import com.jung.common.JqueryGridAction;
import com.jung.customer.action.CustomerAction;
import com.jung.news.model.News;
import com.jung.news.service.NewsService;

public class NewsAction extends JqueryGridAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Log logger = LogFactory.getLog(CustomerAction.class);
	/**
	 * 总页数.
	 */
	private Integer total = 0;

	/**
	 * 总记录数.
	 */
	private Integer records = 0;

	/**
	 * 当前页数.
	 */
	private Integer page = 0;

	/**
	 * 排序字段名称.
	 */
	private String sidx = "";

	/**
	 * 排序方式.
	 */
	private String sord = "desc";

	/**
	 * 每页数量.
	 */
	private Integer rows;

	/**
	 * 查询结果列表.
	 */
	private List<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
	private String result;
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
	private int id;
	private String title;
	private String content;
	private Date publishTime;
	
	private NewsService newsService;
	
	@Resource
	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}
   
	private News news;
	
	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}

	public Date getPublishTime() {
		return publishTime;
	}
	public void setPublishTime(Date publishTime) {
		this.publishTime = publishTime;
	}
	
	
    public Integer getTotal() {
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public Integer getRecords() {
		return records;
	}

	public void setRecords(Integer records) {
		this.records = records;
	}

	public Integer getPage() {
		return page;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public String getSidx() {
		return sidx;
	}

	public void setSidx(String sidx) {
		this.sidx = sidx;
	}

	public String getSord() {
		return sord;
	}

	public void setSord(String sord) {
		this.sord = sord;
	}

	public Integer getRows() {
		return rows;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	public List<Map<String, Object>> getDataRows() {
		return dataRows;
	}

	public void setDataRows(List<Map<String, Object>> dataRows) {
		this.dataRows = dataRows;
	}

	public String execute(){
    	dataRows = new ArrayList<Map<String, Object>>();
		decodeQueryCondition();
		if (this.rows == null || this.rows <= 0) {
			int pagesize = Constants.DEFAULT_PAGE_SIZE;
			this.getPageContext().setPageSize(pagesize);
		} else
			this.getPageContext().setPageSize(rows);
		this.getPageContext().setPageNumber(page > 0 ? page - 1 : 0);
		// 获取支持当前查询的实体类型的查询服务接口定义
		try {
			setPageContext(newsService.getEntityPage(getPageContext(), getQueryConditions(),
					getSidx(), getSord()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (getPageContext()!= null && getPageContext().getPage() != null) {
			this.total = getPageContext().getPage().getLastPageNumber();
			this.records = getPageContext().getPage().getTotalNumberOfElements();
		}
		List entityList = this.getPageContext().getPage().getThisPageElements();
		if (entityList != null && entityList.size() > 0) {
			for (int i = 0; i < entityList.size(); i++) {
				Map<String, Object> dataitem = new HashMap<String, Object>();
				Object entity = entityList.get(i);
				// set rows
				Field[] fields = entity.getClass().getDeclaredFields();
				fields = removeStaticProperty(fields);
				int fieldLength = fields.length;
				for (int j = 0; j < fieldLength; j++) {
					try {
						String getMethodName = "get" + fields[j].getName().substring(0, 1).toUpperCase() + fields[j].getName().substring(1);
						Method getMethod = entity.getClass().getMethod(getMethodName, new Class[] {});
						String returnType = getMethod.getReturnType().getSimpleName();
						if (checkBaseDataType(returnType)) {
							Object obj = getMethod.invoke(entity, new Object[] {});
							String fieldValue = "";
							if (obj != null){
								fieldValue = obj.toString();
							}
							dataitem.put(fields[j].getName(), fieldValue);
						}
					} catch (Exception e) {
						logger.error(e);
					}
				}
				dataRows.add(dataitem);
			}
		}
    	return SUCCESS;
    }
    private boolean decodeQueryCondition() {
		if (getQueryConditions() != null) {
			for (Iterator iter = getQueryConditions().keySet().iterator(); iter
					.hasNext();) {
				String key = (String) iter.next();
				try {
					String inputString = getQueryConditions().get(key);
					inputString = inputString.replaceAll("%26", "&");
					getQueryConditions().put(
							key,
							new String(inputString.getBytes("ISO-8859-1"),
									"GB2312"));
				} catch (UnsupportedEncodingException e) {
					logger.error(e);
					return false;
				}

			}
		}
		return true;
	}
    private boolean checkBaseDataType(String returnType) {
		for (int i = 0; i < Constants.BASE_DATA_TYPE.length; i++) {
			if (Constants.BASE_DATA_TYPE[i].equals(returnType))
				return true;

		}
		return false;
	}
    private static Field[] removeStaticProperty(Field[] fields) {
		Field[] tempFields = new Field[fields.length];
		int count = 0;
		for (int i = 0; i < fields.length; i++) {
			if (fields[i].getModifiers() <= Modifier.PRIVATE) {
				tempFields[count] = fields[i];
				count++;
			}
		}
		Field[] returnFields = new Field[count];
		for (int i = 0; i < count; i++) {
			returnFields[i] = tempFields[i];
		}
		return returnFields;

	}
	public String addNews(){
		News news = new News();
		news.setTitle(title);
		news.setContent(content);
		news.setPublishTime(new Date());
		newsService.addNews(news);
		return SUCCESS;
	}
	public String deleteNews(){
			this.result=newsService.deleteNewsById(id);
		return SUCCESS;
	}
	public String findNewsById(){
		this.news=newsService.findNewsById(id);
		return SUCCESS;
	}
	private Map model;
	public Map getModel() {
		return model;
	}

	public void setModel(Map model) {
		this.model = model;
	}
   public String findNewsNewest(){
	   this.news = newsService.getNewsTheNewest();
	   if(news!=null){
		   this.title = news.getTitle();
		   this.content=news.getContent();
	   }
	   model = new HashMap();
	   model.put("title", title);
	   model.put("content", content);
	   return SUCCESS;
   }
}
